package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.item.entity.TbBrand;
import com.leyou.item.entity.TbCategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.mapper.CategoryBrandMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    ///page?key=&page=1&rows=5&sortBy=id&desc=false
    public PageInfo<TbBrand> queryBrandList(String key, Integer pageNum, Integer pageSize, String sortBy, Boolean dese){
        //分页
        if(pageSize>0)PageHelper.startPage(pageNum,pageSize);
        //过滤
        Example example = new Example(TbBrand.class);
        //排序
        if(sortBy!=null)example.setOrderByClause(sortBy+ " "+(dese?"desc":"asc"));
        //模糊查询
        if(StringUtils.isNotBlank(key))example.createCriteria().andLike("name","%"+key+"%");
        //得到分页集合
        List<TbBrand> tbBrands = brandMapper.selectByExample(example);
        PageInfo<TbBrand> tbBrandPageInfo = new PageInfo<>(tbBrands);
        //返回结果
        return tbBrandPageInfo;
    }
    //添加
    @Transactional
    public void addBrand(TbBrand brand,Long [] cids){
        brandMapper.insertSelective(brand);
        System.out.println(brand.getId());
        //添加中间表
        for (Long cid : cids) {
            brandMapper.addCategoryBrand(cid,brand.getId());

        }
    }
    //修改
    public void updateBrand(TbBrand brand,Long[] cids){
        brandMapper.updateByPrimaryKeySelective(brand);

        TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
        tbCategoryBrand.setBrandId(brand.getId());
        categoryBrandMapper.delete(tbCategoryBrand);//删除中间表中品牌id对应的数据
        for (Long cid : cids) {
            tbCategoryBrand.setCategoryId(cid);
            categoryBrandMapper.insert(tbCategoryBrand);//把我们修改后的品牌与分类的id重新存入到中间表中
        }
    }
    //删除
    public void deleteBrand(Long[] bids){
        Example example = new Example(TbBrand.class);
        example.createCriteria().andIn("id", Arrays.asList(bids));
        brandMapper.deleteByExample(example);
        TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
        for (Long bid : bids) {
            tbCategoryBrand.setBrandId(bid);
            categoryBrandMapper.delete(tbCategoryBrand);
        }
    }

    //根据分类id获取品牌信息
    public List<TbBrand> queryBrandByCid(Long cid){

        return brandMapper.queryBranByCid(cid);
    }

    //根据品牌id获取品牌信息
    public TbBrand queryBrandById(Long bid) {

        return brandMapper.selectByPrimaryKey(bid);
    }
}
